package com.electronic.utils;

import cn.hutool.core.date.DateUtil;
import com.electronic.constant.CommonConstant;
import com.electronic.exception.ResultCode;
import com.electronic.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: IFCA
 * @Description: 处理文件路径工具类
 */
@Component
@Slf4j
public class FilePathUtil {




    /**
     * 产生的中间文件(临时文件)绝对路径
     * @param path
     * @param pid
     * @param suffix
     * @return
     */
    public static String generateFileMiddleAbsolutePath(String path, String pid, String suffix) {
        String dirPath = path + File.separator +"middle";
        exists(dirPath);
        dirPath = dirPath +File.separator + pid + "." + suffix;
        return dirPath;
    }

    /**
     * 生成签署完成文件绝对路径
     * @param path
     * @param suffix
     * @return
     */
    public static String signatureFileSaveFilePath(String path, String fileName, String suffix) {
        String dirPath = path;
        exists(dirPath);
        dirPath = dirPath +File.separator + fileName + "." + suffix;
        return dirPath;
    }
    public static void exists(String dirPath){
        // 创建 File 对象
        File directory = new File(dirPath);
        // 检查文件夹是否存在
        if (!directory.exists()) {
            // 创建文件夹
            if (directory.mkdirs()) {
                log.info("文件夹创建成功--{}",dirPath);
            } else {
                log.error("文件夹创建失败--{}",dirPath);
                throw new ServiceException(ResultCode.ERROR_FILE_FORBIDDEN,ResultCode.ERROR_FILE_FORBIDDEN.getMessage());
            }
        }
    }



    /**
     * 生成日期路径
     *
     * @return
     */
    public static String getDateFilePath() {
        Date now = new Date();
        String monthStr = DateUtil.format(now, CommonConstant.DATE_FORMAT_YYYYMM);
        int day = DateUtil.thisDayOfMonth();
        return monthStr + File.separator + day + File.separator;
    }

    /**
     * 生成文件名称
     *
     * @param fileNamePrefix
     * @param transactionId
     * @param fileType
     * @return
     */
    public static String getFileName(String fileNamePrefix, String transactionId, String fileType) {
        StringBuilder fileName = new StringBuilder();
        if (Objects.nonNull(fileNamePrefix)) {
            fileName.append(fileNamePrefix).append("_");
        }
        fileName.append(transactionId).append(CommonConstant.FILE_EXTENSION_SEPARATOR).append(fileType);
        return fileName.toString();
    }


}
